package com.am.mosl.cityandroid.mainboard;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.core.AsyncTask;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.am.mosl.cityandroid.R;
import com.am.mosl.cityandroid.activity.BaseActivity;
import com.am.mosl.cityandroid.bean.AccountBean;
import com.am.mosl.cityandroid.bean.City;
import com.am.mosl.cityandroid.bean.Column;
import com.am.mosl.cityandroid.citychange.CityChangeActivity;
import com.am.mosl.cityandroid.constant.HttpConstant;
import com.am.mosl.cityandroid.message.CityChangeMessage;
import com.am.mosl.cityandroid.message.LoginMessage;
import com.am.mosl.cityandroid.message.MessageNumber;
import com.am.mosl.cityandroid.parser.JSONParser;
import com.am.mosl.cityandroid.util.CityPerferenceUtil;
import com.am.mosl.cityandroid.util.LocationUtils;
import com.am.mosl.cityandroid.util.SettingUtils;
import com.am.mosl.cityandroid.widget.CircleImageView;
import com.am.mosl.cityandroid.widget.DrawerView;
import com.am.mosl.cityandroid.widget.PagerSlidingTabStrip;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.nostra13.universalimageloader.core.ImageLoader;

import de.greenrobot.event.EventBus;

public class MainActivity extends BaseActivity {

	public static final String TAG = "FragmentActivity";
	private TextView city;
	private List<Column> mColumnList = new ArrayList<Column>();
	protected SlidingMenu mSildeMenu; // 左滑菜单

	private ViewPager mViewPager;
	private DrawerView mDrawerView;
	private CircleImageView mUser_image;
	private String mLocateCityName;
	public static  int mCityId = -1;

    FinalHttp finalHttp = new FinalHttp();
    private MyFragmentPageAdapter mFragmentAdapter;
    private PagerSlidingTabStrip slidingTabStrip;

    private View mViewPagerLayout;
    private View mNoData;
    boolean isExit;  
    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        if (keyCode == KeyEvent.KEYCODE_BACK) {  
            exit();  
            return false;  
        } else {  
            return super.onKeyDown(keyCode, event);  
        }  
    }  
    public void exit(){  
        if (!isExit) {  
            isExit = true;  
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();  
            mHandler.sendEmptyMessageDelayed(0, 2000);  
        } else {  
            Intent intent = new Intent(Intent.ACTION_MAIN);  
            intent.addCategory(Intent.CATEGORY_HOME);  
            startActivity(intent);  
            System.exit(0);  
        }  
    }  
    Handler mHandler = new Handler() {  

    	  

        @Override  

        public void handleMessage(Message msg) {  

            // TODO Auto-generated method stub   

            super.handleMessage(msg);  

            isExit = false;  

        }  

  

    };  
    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		JPushInterface.init(this);
		if (SettingUtils.IsLogin(this)) {

			AccountBean accountBean = new AccountBean();
			accountBean = SettingUtils.getUserInfo(MainActivity.this);
			String uid = accountBean.data.getUid();
			JPushInterface.setAlias(MainActivity.this, uid, null);

		}
		initSlidingMenu(); // 初始化滑动菜单
		initViews();
        initViewPager();
		registerBus();
		getCityByIp();

	}


    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    private void getCityByIp() {
        new IpTask().execute();
	}

	private void registerBus() {
		EventBus.getDefault().register(this, "Userlogin", LoginMessage.class);
		EventBus.getDefault().register(this, "cityChange",CityChangeMessage.class);
        EventBus.getDefault().register(this,"messageNumber", MessageNumber.class);
	}

	public void Userlogin(LoginMessage message) {
		// 1登录 2注销 0更新
		if (message.getType() == LoginMessage.LOGIN) {
			mDrawerView.updateSlideMenu();
			mUser_image.tipVisibility=0;
			String imageUrl = SettingUtils.getUserInfo(MainActivity.this)
					.getData().getHead_img();
			if (imageUrl != null) {
				ImageLoader.getInstance().displayImage(imageUrl, mUser_image);
			}
		}
		if (message.getType() == LoginMessage.QUIT) {

			mUser_image.tipVisibility=0;
			mDrawerView.updateSlideMenu();
			mUser_image.setImageResource(R.drawable.avatar_default);
		}
		
		if (message.getType() == LoginMessage.SPOT) {

			mDrawerView.updateSlideMenu();
			mUser_image.tipVisibility=1;
			String imageUrl = SettingUtils.getUserInfo(MainActivity.this)
					.getData().getHead_img();
			if (imageUrl != null) {
				ImageLoader.getInstance().displayImage(imageUrl, mUser_image);
			}
		
		}

	}

	private void cityChange(CityChangeMessage message) {

		String CityId = Integer.toString(message.getCityId());
        Log.d("momo",message.getCityName()+message.getCityId());
		if (!CityId.endsWith(Integer.toString(mCityId))) {
			mLocateCityName = message.getCityName();
            city.setText(mLocateCityName);
			GetColumn(CityId);
			mCityId = Integer.parseInt(CityId); //设置当前的Id

            City city1=new City();
            city1.setId(message.getCityId());
            city1.setCity(message.getCityName());
            CityPerferenceUtil.putLaterestCity(this,city1);

            mColumnList.clear();
            slidingTabStrip.clearTab();
		}

	}

    private void messageNumber(MessageNumber message){

        int status = message.getStatus();
        if(status==MessageNumber.Status_Set){
            int number = message.getNumber();
            mDrawerView.setMessageNumebr(number);
        }

        if(status ==MessageNumber.Status_Cancel){
            mDrawerView.setMessageNumebr(-1);
        }
    }
    private void getCityMessage(String cityId){
        Log.d(TAG,cityId);
        mCityId=Integer.parseInt(cityId);
        GetColumn(cityId);
    }

	private void initViews() {
		if (SettingUtils.IsLogin(this)) {
			String imageUrl = SettingUtils.getUserInfo(MainActivity.this)
					.getData().getHead_img();
			if (imageUrl != null)
				ImageLoader.getInstance().displayImage(imageUrl, mUser_image);
		}
        mViewPagerLayout=(View)findViewById(R.id.fragment_viewpager_layout);
        mNoData = (View)findViewById(R.id.nocolumn);

        city = (TextView) findViewById(R.id.city);
        city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.this.startActivity(new Intent(MainActivity.this,
                        CityChangeActivity.class));
            }
        });
        slidingTabStrip = (PagerSlidingTabStrip)findViewById(R.id.SlidingTabStrip);
	}

	private void initTabColumn(List<Column> columnList) {
		int count = columnList.size();
        List<View> columnListView = new ArrayList<View>();
		for (int i = 0; i < count; i++) {
			Column column = columnList.get(i);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.MATCH_PARENT,
                    Gravity.CENTER_VERTICAL);
			params.leftMargin = 10;
			params.rightMargin = 10;
			TextView columnTextView = new TextView(this);
            columnTextView.setLayoutParams(params);
			columnTextView.setTextAppearance(this,
					R.style.top_category_scroll_view_item_text);
		    columnTextView.setBackgroundResource(R.drawable.selector_slide_title);
			columnTextView.setPadding(20, 20, 13, 20);
			columnTextView.setId(i);
			columnTextView.setText(column.getColumn());
			columnTextView.setTextColor(getResources().getColorStateList(
					R.color.top_category_scroll_text_color_day));
            columnListView.add(columnTextView);
		}
        slidingTabStrip.addTab(columnListView);
	}

    //获得栏目
    public final void GetColumn(String cityId){
        AjaxParams params=new AjaxParams();
        params.put("cityid", cityId);
        finalHttp.post(HttpConstant.ColomnHttp, params, new AjaxCallBack<Object>() {
            @Override
            public boolean isProgress() {
                return super.isProgress();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Log.d(TAG,strMsg+"onFailure");
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                try {
                    JSONObject jsonObject = new JSONObject(o.toString());
                    String status = (String)jsonObject.opt("status");
                    if("1".endsWith(status)){
                        JSONArray jsonArray = (JSONArray) jsonObject.opt("data");
                        List<Column> list = JSONParser.getListColumn(jsonArray.toString());
                        mColumnList.clear();
                        mColumnList.addAll(list);
                        slidingTabStrip.clearTab();
                        initTabColumn(mColumnList);
                        slidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                            @Override
                            public void onPageScrolled(int i, float v, int i2) {

                            }
                            @Override
                            public void onPageSelected(int i) {

                                switch (i) {
                                    case 0:
                                        mSildeMenu
                                                .setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
                                        break;
                                    default:
                                        mSildeMenu
                                                .setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
                                }
                            }

                            @Override
                            public void onPageScrollStateChanged(int i) {

                            }
                        });
                        mFragmentAdapter = new MyFragmentPageAdapter(getSupportFragmentManager(), Integer.toString(mCityId), mColumnList);
                        mFragmentAdapter.notifyDataSetChanged();
                        mViewPager.destroyDrawingCache();
                        mViewPager.setAdapter(mFragmentAdapter);
                        slidingTabStrip.setViewPager(mViewPager);
                        mViewPager.setDrawingCacheEnabled(true);
                        mViewPagerLayout.setVisibility(View.VISIBLE);
                        mNoData.setVisibility(View.GONE);
                    }

                    if("0".endsWith(status)){
                        mColumnList.clear();
                        slidingTabStrip.clearTab();
                        mViewPagerLayout.setVisibility(View.GONE);
                        mNoData.setVisibility(View.VISIBLE);
                        Toast.makeText(MainActivity.this, "当前城市没有数据", Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }


	protected void initSlidingMenu() {
		mDrawerView = new DrawerView(MainActivity.this);
		mSildeMenu = mDrawerView.initSlidingMenu();
		mSildeMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); // 全屏滑动
		mUser_image = (CircleImageView) findViewById(R.id.user_image);
		mUser_image.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				if (mSildeMenu.isMenuShowing()) {
					mSildeMenu.showContent();
				} else {
					mSildeMenu.showMenu();
				}
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unRegisterEventBus();
	}

	private void unRegisterEventBus() {

		EventBus.getDefault().unregister(LoginMessage.class);
		EventBus.getDefault().unregister(CityChangeMessage.class);
        EventBus.getDefault().unregister(MessageNumber.class);
	}

	private void initViewPager() {
		mViewPager = (ViewPager) findViewById(R.id.fragment_viewpager);
		final FragmentManager fm = getSupportFragmentManager();
        mFragmentAdapter = new MyFragmentPageAdapter(fm, Integer.toString(mCityId), mColumnList);
		mViewPager.setAdapter(mFragmentAdapter);
	}

	class IpTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {

			 return LocationUtils.getCNBylocation(MainActivity.this);

		}

		@Override
		protected void onPostExecute(String s) {
			super.onPostExecute(s);
			City localCity = CityPerferenceUtil.getLaterestCity(MainActivity.this);
			/*if(null!=localCity){
				 city.setText(localCity.getCity());
                 GetColumn(Integer.toString(localCity.getId()));
                 mCityId=localCity.getId();
			}else{*/
				//if (s == null || s.length() == 0) {
	                City city1= CityPerferenceUtil.getLaterestCity(MainActivity.this);
	                if(city1.getId()>0){
	                    city.setText(city1.getCity());
	                    GetColumn(Integer.toString(city1.getId()));
	                    mCityId=city1.getId();
	                }else{
	                    city.setText("燕郊");
	                    GetColumn(Integer.toString(17));
	                    mCityId=17;
	                }
	           /* }
				else{
					//TODO地区指定
					s="燕郊";
	                mLocateCityName=s;
	                city.setText(s);
	                GetIdByCityName(s);
	            }*/

			}
			

		//}
	}

    private void GetIdByCityName(String cityName) {
        AjaxParams params = new AjaxParams();
        params.put("cityname",cityName);
        finalHttp.post(HttpConstant.GetIdByCityName,params,new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);

                try {
                    JSONObject jsonObject = new JSONObject(o.toString());
                    Log.d(TAG,jsonObject.toString());
                    String status = (String)jsonObject.opt("status");
                    if(status.endsWith("1")){
                        String id = (String)jsonObject.opt("id");
                        mLocateCityName = (String)jsonObject.opt("city");
                        city.setText(mLocateCityName);
                        getCityMessage(id);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

	public class MyFragmentPageAdapter extends FragmentStatePagerAdapter {
		private List<Column> columnList;
		private String cityId;
        private FragmentManager mManager;
        private Map<Integer, String> tagList = null;
		public MyFragmentPageAdapter(FragmentManager fm, String cityId,
				List<Column> columnList) {
			super(fm);
            mManager=fm;
			this.columnList = columnList;
			this.cityId = cityId;
            tagList = new HashMap<Integer, String>();
		}

		@Override
		public int getCount() {
			return columnList.size();
		}

		@Override
		public Fragment getItem(int position) {
			return new FragmentMain(cityId,
					Integer.toString(columnList.get(position).getId()));
		}
    }

	@Override
	public void onBackPressed() {
		if (mSildeMenu.isMenuShowing()) {
			mSildeMenu.showContent();
		} else {
			super.onBackPressed();
		}
	}

}
